package com.example.demo.web;

import com.example.demo.core.Result;
import com.example.demo.core.ResultGenerator;
import com.example.demo.model.Student;
import com.example.demo.service.impl.StudentServiceImpl;
import com.example.demo.support.MyFileUtil;
import com.example.demo.support.PoiUtils;
import lombok.extern.slf4j.Slf4j;


import org.apache.poi.ss.usermodel.*;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Kevin
 * @date 2020/4/19 23:27
 */
@RestController
@RequestMapping(value = "/file")
@Slf4j
public class FileController {
    @Resource
    private StudentServiceImpl studentService;

    @RequestMapping(value = "/upload")
    public Result upload(@RequestParam("file")MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResultGenerator.genFailResult("File is empty!");
            }
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if (!suffixName.equals(".xls") && !suffixName.equals(".xlsx")) {
                return ResultGenerator.genFailResult("File is illegal!");
            }
            log.info("文件的上传名为：" + fileName + "，后缀名为" + suffixName);
            // 设置上传文件的路径，这里设置上传到类路径下
            String ap = ResourceUtils.getFile("classpath:").getAbsolutePath();
            File dest = new File(ap, "static/upload_file/"+fileName);
            //执行文件上传复制
            file.transferTo(dest);
            //保存文件后，解析文件
            analysisExcel(dest);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("Upload Failed! FileNotFound!");
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("Upload Failed! IOException!");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("Upload Failed! Analysis Failed!");
        }
        // 跳转页面
        return ResultGenerator.genSuccessResult("Upload success!");
    }

    /**将Ecel解析出来*/
    @Transactional(propagation = Propagation.REQUIRED)
    public void analysisExcel(File file) throws Exception {
        InputStream inputStream = new FileInputStream(file);
        Workbook workbook = WorkbookFactory.create(inputStream);
        inputStream.close();

        Sheet sheet = workbook.getSheetAt(0);                 //第一个sheet
        int rowLength = sheet.getLastRowNum()+1;                 //总行数
        int colLength = sheet.getRow(0).getLastCellNum();   //总列数

        //得到单元格样式
        /**
        * 这里只是简单的输出，可以格式转换后  构造对象，加入集合，调用StudentMapper.save(List<Student> students)保存
         */
        System.out.println("行数：" + rowLength + ",列数：" + colLength);
        for (int i = 0; i < rowLength; i++) {
            Row row = sheet.getRow(i);
            for (int j = 0; j < colLength; j++) {
                Cell cell = row.getCell(j);
                //Excel数据Cell有不同的类型，当我们试图从一个数字类型的Cell读取出一个字符串时就有可能报异常：
                //Cannot get a STRING value from a NUMERIC cell
                //将所有的需要读的Cell表格设置为String格式
                if (cell != null){
                    cell.setCellType(CellType.STRING);
                    System.out.print(cell.getStringCellValue() + "\t");
                }
            }
            System.out.println();
        }

        // 保存到数据库
        // 这里再次打开了file,操作冗余，有空待改进
        List<Student> students = PoiUtils.readExcel(file.getAbsolutePath());
        // 执行保存
        studentService.save(students);
    }


    @RequestMapping("/download")
    public Result Download(String fileName, HttpServletResponse response, HttpSession session) throws Exception {
        MyFileUtil.downloadHelper(fileName, response);
        return ResultGenerator.genSuccessResult("Download success!");
    }
}
